package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.CustomerUserDao;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.subform.ContactTeamEnum;
import com.xbongbong.saas.enums.subform.CustomerTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.IndexTypeModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;


/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/25 10:20
 * @since v1.0
 */

@Component
@Service("customerUserModel")
public class CustomerUserModelImpl implements CustomerUserModel {
    @Resource
    private CustomerUserDao customerUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private IndexTypeModel indexTypeModel;


    @Override
    public Integer insert(CustomerUserEntity customerUserEntity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        customerUserEntity.setAddTime(now);
        customerUserEntity.setUpdateTime(now);
        Integer result = customerUserDao.insert(customerUserEntity);

        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM, customerUserEntity);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(customerUserEntity.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, indexTypeEnum);
        paasEsModel.insert(insertDTO);
        return result;
    }

    @Override
    public Integer update(CustomerUserEntity customerUserEntity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        customerUserEntity.setUpdateTime(now);
        Integer result = customerUserDao.update(customerUserEntity);
        if (Objects.equals(1, result)) {
            PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM, customerUserEntity);
            IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(customerUserEntity.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

            InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, indexTypeEnum);
            paasEsModel.update(saveDTO);
        }
        return result;
    }

    @Override
    public List<CustomerUserEntity> findEntitys(Map<String, Object> param) {
        return customerUserDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return customerUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public Integer save(CustomerUserEntity customerUserEntity) throws XbbException {
        if (customerUserEntity.getId() == null || customerUserEntity.getId().equals(0L)) {
           return insert(customerUserEntity);
        }
        return update(customerUserEntity);
    }

    @Override
    public CustomerUserEntity getByKey(Long key, String corpid) {
        return customerUserDao.getByKey(key, corpid);
    }

    @Override
    public List<String> getCustomerUserIdList(String corpid, List<Long> customerIds, Integer isMain) {
        return customerUserDao.getCustomerUserIdList(corpid, customerIds, isMain);
    }
    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return customerUserDao.getDataIdList(corpid,isMain,userId);
    }

    @Override
    public List<Long> getDataIdList4Rule(String corpid, Integer isMain, String userId, Long startId, Integer pageNum) {
        return customerUserDao.getDataIdList4Rule(corpid,isMain,userId, startId, pageNum);
    }

    @Override
    public void batchUpgrade(String corpid, List<CustomerUserEntity> customerUsers, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        customerUserDao.batchUpgrade(corpid, customerUsers);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<InsertDTO> insertList = new ArrayList<>();
        for (CustomerUserEntity entity : customerUsers){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            JSONObject object = new JSONObject();
            object.put(CustomerTeamEnum.IS_MAIN.getDataAttr(), 1);
            map.put(StringConstant.JSON_DATA, object);
            map.put("updateTime", DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public void deleteBatch(String corpid, List<CustomerUserEntity> customerUsers, WriteRequest.RefreshPolicy refreshPolicy, Integer del) throws XbbException {
        if (CollectionUtils.isEmpty(customerUsers)) {
            return;
        }
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<Long> removeIdList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (CustomerUserEntity entity : customerUsers){
            removeIdList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("del", del);
            map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertDTOList.add(insertDTO);
        }
        customerUserDao.batchDeleteById(corpid,removeIdList, del);
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
    }

    @Override
    public void insertBatch(List<CustomerUserEntity> customerUserEntityList, boolean isImport) throws XbbException{
        if (CollectionUtils.isEmpty(customerUserEntityList)) {
            return;
        }
        customerUserDao.insertBatch(customerUserEntityList);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM, customerUserEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(customerUserEntityList.get(0).getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, indexTypeEnum));
        }
        if (isImport) {
            paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.insertBatch(insertDTOList);
        }

    }

    @Override
    public void disbandedTeam(String corpid, List<Long> customerIdList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        Map<String,Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid",corpid);
        params.put("del",-1);
        params.put("customerIdIn",customerIdList);
        List<CustomerUserEntity> perCustomerUserEntityList = findEntitys(params);

        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<InsertDTO> preUpdateBatch = new ArrayList<>();
        List<Long> preIdList = new ArrayList<>();
        if (!perCustomerUserEntityList.isEmpty()) {
            for (CustomerUserEntity entity : perCustomerUserEntityList) {
                preIdList.add(entity.getId());
                InsertDTO insertDTO = new InsertDTO();
                insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
                insertDTO.setParent(corpid + "_" + entity.getDataId());
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("del", 1);
                map.put("updateTime", DateTimeUtil.getInt());
                JSONObject object = new JSONObject();
                object.put(CustomerTeamEnum.DISTRIBUTION_TIME.getDataAttr(), DateTimeUtil.getInt());
                map.put(StringConstant.JSON_DATA, object);
                insertDTO.setSource(map);
                insertDTO.setIndexTypeEnum(indexTypeEnum);
                preUpdateBatch.add(insertDTO);
            }
            customerUserDao.batchDeleteById(corpid, preIdList, DelEnum.DELETE.getDel());
            if (Objects.nonNull(refreshPolicy)) {
                paasEsModel.updateBatch(preUpdateBatch, refreshPolicy);
            } else {
                paasEsModel.updateBatch(preUpdateBatch);
            }
        }
        params.put("del",0);
        List<CustomerUserEntity> customerUserEntityList = findEntitys(params);
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> updateBatch = new ArrayList<>();
        for (CustomerUserEntity entity : customerUserEntityList){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("del", -1);
            map.put("updateTime", DateTimeUtil.getInt());
            JSONObject object = new JSONObject();
            object.put(CustomerTeamEnum.DISTRIBUTION_TIME.getDataAttr(), DateTimeUtil.getInt());
            map.put(StringConstant.JSON_DATA, object);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            updateBatch.add(insertDTO);
        }
        customerUserDao.disbandedTeam(corpid,idList);
        if (Objects.nonNull(refreshPolicy)) {
            paasEsModel.updateBatch(updateBatch, refreshPolicy);
        } else {
            paasEsModel.updateBatch(updateBatch);
        }
    }

    @Override
    public void batchDeleteByCustomerId(String corpid, List<Long> customerIdIn, List<String> userIdList) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("customerIdIn",customerIdIn);
        map.put("userIdIn",userIdList);
        List<CustomerUserEntity> customerUserEntityList = findEntitys(map);
        customerUserDao.batchDelete(corpid,customerIdIn,userIdList);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        for (CustomerUserEntity entity : customerUserEntityList){
            paasEsModel.delete(entity.getId(), corpid, indexTypeEnum,entity.getDataId());
        }
    }

    @Override
    public void batchDeleteTeam(String corpid, List<Long> customerIdIn, List<String> userIdList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("customerIdIn",customerIdIn);
        map.put("userIdIn",userIdList);
        List<CustomerUserEntity> customerUserEntityList = findEntitys(map);
        customerUserDao.batchDelete(corpid,customerIdIn,userIdList);

        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (CustomerUserEntity entity : customerUserEntityList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> sourceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            sourceMap.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            insertDTO.setSource(sourceMap);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
    }

    @Override
    public Map<Long, Set<String>> batchDeleteById(String corpid, List<Long> removeIdList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("idIn",removeIdList);
        List<CustomerUserEntity> customerUserEntityList = findEntitys(map);
        customerUserDao.batchDeleteById(corpid,removeIdList, DelEnum.DELETE.getDel());
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<Long, Set<String>> customerUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (CustomerUserEntity entity : customerUserEntityList){
            Set<String> orDefault = customerUserMap.getOrDefault(entity.getDataId(), new HashSet<>());
            orDefault.add(entity.getUserId());
            customerUserMap.put(entity.getDataId(),orDefault);
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertDTO.setIndex(indexTypeEnum.getIndex());
            insertDTO.setType(indexTypeEnum.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL,DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return customerUserMap;
    }

    @Override
    public void delete(CustomerUserEntity customerUser) throws XbbException{
        customerUser.setDel(1);
        customerUser.setUpdateTime((long) DateUtil.getInt());
        customerUserDao.update(customerUser);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(customerUser.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        paasEsModel.delete(customerUser.getId(), customerUser.getCorpid(), indexTypeEnum, customerUser.getDataId());
    }

    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return customerUserDao.findBaseEntitys(map);
    }

    @Override
    public Integer updateBatch(List<CustomerUserEntity> list, String corpid) throws XbbException{
        return updateBatch(list, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public Integer updateBatch(List<CustomerUserEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy ) throws XbbException{
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }

        Integer result = customerUserDao.updateBatch(list, corpid);
        List<InsertDTO> insertList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        for (CustomerUserEntity entity : list){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(entity.getDel())) {
                map.put("del", entity.getDel());
            }
            map.put("updateTime", DateTimeUtil.getInt());
            JSONObject object = new JSONObject();
            if (Objects.nonNull(entity.getDistributionTime())) {
                object.put(CustomerTeamEnum.DISTRIBUTION_TIME.getDataAttr(), entity.getDistributionTime());
            }
            if (Objects.nonNull(entity.getIsMain())) {
                object.put(ContactTeamEnum.IS_MAIN.getDataAttr(), entity.getIsMain());
            }
            if (Objects.nonNull(entity.getDataId())) {
                object.put(CustomerTeamEnum.DATA_ID.getDataAttr(), entity.getDataId());
            }
            if (Objects.nonNull(entity.getUserId())) {
                object.put(CustomerTeamEnum.USER_ID.getDataAttr(), entity.getUserId());
            }
            if (Objects.nonNull(entity.getUserName())) {
                object.put(CustomerTeamEnum.USER_NAME.getDataAttr(), entity.getUserName());
            }
            if (Objects.nonNull(entity.getUserAvatar())) {
                object.put(CustomerTeamEnum.USER_AVATAR.getDataAttr(), entity.getUserAvatar());
            }
            if (Objects.nonNull(entity.getBackTime())) {
                object.put(CustomerTeamEnum.BACK_TIME.getDataAttr(), entity.getBackTime());
            }
            map.put(StringConstant.JSON_DATA, object);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
        return result;
    }

    @Override
    public void initPreUser(List<CustomerUserEntity> customerUserEntityList) throws XbbException {

    }

    @Override
    public List<PaasFormDataEntityExt> setLastMainPerson(List<PaasFormDataEntityExt> customerList, String corpid) {
        List<Long> customerIdIn = new ArrayList<>();
        customerIdIn.add(-1L);
        for(PaasFormDataEntityExt customerEntity : customerList){
            customerIdIn.add(customerEntity.getDataId());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("customerIdIn", customerIdIn);
        param.put("isMain", 1);
        param.put("corpid", corpid);
        param.put("orderByStr", "customer_id desc,back_time desc");
        param.put("del", DelEnum.DELETE.getDel());
        //前负责人们
        List<CustomerUserEntity> customerUserList = findEntitys(param);
        Long lastBackTime=null;
        Long lastCustomerId=null;
        Map<Long, String> customerUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for(CustomerUserEntity customerUserEntity : customerUserList){
            Long customerId = customerUserEntity.getDataId();
            //遍历下一个客户
            if(lastCustomerId!=null && !lastCustomerId.equals(customerId)){
                lastCustomerId=customerId;
                lastBackTime=customerUserEntity.getBackTime();
            }else{
                if(lastBackTime!=null && customerUserEntity.getBackTime() != null && lastBackTime > customerUserEntity.getBackTime()){
                    lastCustomerId=customerId;
                    continue;
                }else{
                    lastBackTime=customerUserEntity.getBackTime();
                    lastCustomerId=customerId;
                }

            }

            String customerUserName = customerUserMap.get(customerId);
            if(StringUtil.isEmpty(customerUserName)){
                customerUserName = "";
            }
            if(StringUtil.isEmpty(customerUserName)){
                customerUserName = customerUserEntity.getUserName();
            }else{
                customerUserName += "，" + customerUserEntity.getUserName();
            }
            customerUserMap.put(customerId, customerUserName);
        }

        for(PaasFormDataEntityExt customerEntity : customerList){
            String customerUser  = customerUserMap.get(customerEntity.getDataId());
            if(!StringUtil.isEmpty(customerUser) ){
                JSONObject data = customerEntity.getData();
                data.put(FieldTypeEnum.OWNERID.getAlias(), customerUser);
                customerEntity.setData(data);
            }
        }

        return customerList;
    }

    @Override
    public void initPreUser(String corpid, Long customerId) throws XbbException{
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("customerId",customerId);
        //前负责人
        param.put("del",-1);
        List<CustomerUserEntity> customerUserEntityList = findEntitys(param);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        if (!customerUserEntityList.isEmpty()) {
            List<InsertDTO> insertList = new ArrayList<>();
            for (CustomerUserEntity entity : customerUserEntityList) {
                entity.setDel(-1);
                InsertDTO insertDTO = new InsertDTO();
                insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
                insertDTO.setParent(corpid + "_" + entity.getDataId());
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("del", -1);
                map.put("updateTime", DateTimeUtil.getInt());
                JSONObject object = new JSONObject();
                object.put(CustomerTeamEnum.DISTRIBUTION_TIME.getDataAttr(), DateTimeUtil.getInt());
                map.put(StringConstant.JSON_DATA, object);
                insertDTO.setSource(map);
                insertDTO.setIndexTypeEnum(indexTypeEnum);
                insertList.add(insertDTO);
            }
            customerUserDao.updateBatch(customerUserEntityList, corpid);
            paasEsModel.updateBatch(insertList);
        }
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> userTeamEntityList, Integer isMain, Integer del) throws XbbException {
        customerUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);

        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : userTeamEntityList) {
            String route = corpid + "_" + userTeamEntity.getDataId();
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(route);
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(CustomerTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            String relations = "{\"name\":\"" + indexTypeEnum.getType() + "\",\"parent\":\"" + route  +"\"}";
            map.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(relations));
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> userTeamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        customerUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : userTeamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(CustomerTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public CustomerUserEntity getByUserIdCustomerId(String corpid, String userId, Integer customerId) {
        List<CustomerUserEntity> list = customerUserDao.getByUserIdCustomerId(corpid, userId, customerId);
        CustomerUserEntity customerUser = null;
        if(list.size() > 0){
            customerUser = list.get(0);
        }
        return customerUser;
    }

    @Override
    public List<Long> getDataIdForTempJob(String corpid, List<Long> customerIdList) {
        return customerUserDao.getDataIdForTempJob(corpid,customerIdList);
    }

    @Override
    public List<CustomerUserEntity> getByCustomerId(String corpid, Long customerId) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(StringConstant.DATA_ID, customerId);
        return findEntitys(param);
    }

    /**
     * 隔离模式下解散团队
     *
     * @param shouldUpdateUserTeamList
     */
    @Override
    public void isolationDisbandedTeam(String corpid, List<UserTeamEntity> shouldUpdateUserTeamList, List<Long> shouldUpdateIdList) throws XbbException {
        customerUserDao.batchDeleteById(corpid,shouldUpdateIdList, DelEnum.DELETE.getDel());
        Long updateTime = DateTimeUtil.getInt();
        List<InsertDTO> insertList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        for (UserTeamEntity entity : shouldUpdateUserTeamList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("updateTime", updateTime);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, WriteRequest.RefreshPolicy.NONE);
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param customerUserEntity
     */
    @Override
    public void updateEditFormPer(CustomerUserEntity customerUserEntity) throws XbbException {
        updateFormTeam(customerUserEntity);
    }

    /**
     * 修改团队名称
     *
     * @param customerUserEntity
     */
    @Override
    public void renameTeam(CustomerUserEntity customerUserEntity) throws XbbException {
        updateFormTeam(customerUserEntity);
    }

    /**
     * 编辑团队成员标签
     *
     * @param customerUserEntity
     */
    @Override
    public void editLabel(CustomerUserEntity customerUserEntity) throws XbbException {
        updateFormTeam(customerUserEntity);
    }

    /**
     * 批量更新团队中的协同人的负责人信息
     *
     * @param idIn 团队表中的主键id
     * @param updateUserTeamMainList 更新协同人的负责人信息
     */
    @Override
    public void batchUpdateTeamMainByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> updateUserTeamMainList) throws XbbException {
        batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.WAIT_UNTIL);

    }

    @Override
    public void batchUpdateTeamMainByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> updateUserTeamMainList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        customerUserDao.batchUpdateTeamMain(updateUserTeamMainList, updateTime);
        List<InsertDTO> insertList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        for (UserTeamEntity userTeamEntity : updateUserTeamMainList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("updateTime", updateTime);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }



    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);

    }


    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        customerUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }


    private void updateFormTeam(CustomerUserEntity customerUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        customerUserEntity.setUpdateTime(updateTime);
        customerUserDao.update(customerUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = customerUserEntity.getCorpid();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        insertDTO.setEsId(indexTypeEnum.getType() + "_" + corpid + "_" + customerUserEntity.getId());
        insertDTO.setParent(corpid + "_" + customerUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(indexTypeEnum);
        paasEsModel.update(insertDTO);
    }
}